<template>
  <div class="modal">
    <el-dialog v-model="dialogVisible" title="新建用户" width="30%" center>
      <div class="form">
        <el-form :modal="formData" label-width="80px" size="large">
          <el-form-item label="部门名称" prop="name">
            <el-input
              v-model="formData.name"
              placeholder="请输入部门名称"
            ></el-input>
          </el-form-item>
          <el-form-item label="部门领导" prop="leader">
            <el-input
              v-model="formData.leader"
              placeholder="请输入部门领导"
            ></el-input>
          </el-form-item>
          <el-form-item label="选择部门" prop="parentId">
            <el-select
              v-model="formData.parentId"
              placeholder="请选择部门"
              style="width: 100%"
            >
              <el-option
                v-for="item in entireDepartments"
                :key="item.value"
                :label="item.name"
                :value="item.id"
              />
            </el-select>
          </el-form-item>
        </el-form>
      </div>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="dialogVisible = false">取消</el-button>
          <el-button type="primary" @click="handleConfirmClick">
            确定
          </el-button>
        </span>
      </template>
    </el-dialog>
  </div>
</template>

<script setup lang="ts">
import { reactive, ref } from 'vue'
import { useMainStore } from '@/stores/main/main'
import { storeToRefs } from 'pinia'
import { useSystemStore } from '@/stores/main/system/stytem'

const dialogVisible = ref(false)
const isNewRef = ref(true)
const formData = reactive({
  name: '',
  leader: '',
  parentId: ''
})
const editData = ref()
// 设置show或者hide
function setModalVisible(hasNew: boolean = true, data?: any) {
  dialogVisible.value = true
  // 判断密码框是否显示
  isNewRef.value = hasNew
  if (!hasNew && data) {
    // 编辑用户回显数据
    for (const key in data) {
      formData[key] = data[key]
    }
    editData.value = data
  } else {
    // 新建用户清空数据
    for (const key in formData) {
      formData[key] = ''
    }
    console.log(formData)

    editData.value = null
  }
}

// 获取role数据
const mainStore = useMainStore()
const { entireDepartments } = storeToRefs(mainStore)
// 新建用户的store
const systemStore = useSystemStore()

// 确定按钮逻辑
function handleConfirmClick() {
  dialogVisible.value = false
  if (!isNewRef.value && editData.value) {
    // 编辑数据
    systemStore.editPageDataAction('department', editData.value.id, formData)
  } else {
    //创建新的用户
    systemStore.newPageDataAction('department', formData)
  }
}
// 暴露
defineExpose({ setModalVisible })
</script>

<style lang="scss" scoped></style>
